from jy.trec_qa.trec_processing import clean_text, cut_word, remove_stop_words
from jy.trec_qa.trec_word2vector import get_tokenizer
from jy.trec_qa.trec_constant import Trec_Const
from sklearn.metrics import accuracy_score
from sklearn.metrics import precision_score, recall_score, f1_score
from tensorflow.keras.preprocessing.sequence import pad_sequences
import numpy as np
import tensorflow as tf
from jy.trec_qa.trec_word2vector import get_train_val, build_matrix


def text_to_sequence(text):
    tokenizers = get_tokenizer()
    text = clean_text(text)
    text = cut_word(text)
    text = remove_stop_words(text)
    sequences = tokenizers.texts_to_sequences([text])
    text_num = pad_sequences(sequences, maxlen=Trec_Const.MAX_SEQUENCE_LENGTH)
    return text_num


def predict(text):
    x_train, y_train, x_test, y_test, x_val, y_val = get_train_val()
    model = tf.keras.models.load_model(Trec_Const.trec_model_path, compile=False)
    # model.compile(tf.optimizers.Adam(learning_rate=0.001),
    #               loss='categorical_crossentropy',
    #               metrics=['accuracy'])
    # model.evaluate(x_test, y_test, batch_size=10)
    y_pred = model.predict(x_test)
    y_pred = np.argmax(y_pred, axis=1)
    y_true = np.argmax(y_test, axis=1)

    precision = precision_score(y_true, y_pred, average='weighted')
    recall = recall_score(y_true, y_pred, average='weighted')
    f1 = f1_score(y_true, y_pred, average='weighted')

    text_label = model.predict(text_to_sequence(text))
    text_label = np.argmax(text_label, axis=1)[0]

    result = Trec_Const.labels[text_label]
    return result, '%.3f' % precision, '%.3f' % recall, '%.3f' % f1

# if __name__ == '__main__':
#     text = "animal What fowl grabs the spotlight after the Chinese Year of the Monkey ?"
#     print(predict(text))
